﻿namespace Resonator.Core.Services
{
	using System.Collections.Generic;
	using System.Globalization;
	using System.IO;
	using System.Resources;
	using Models;
	using Resonator.Domain.Models;
	using Resonator.Domain.Services;

	public class ResxResourceExporter : IResourceExporter
	{
		public virtual void Export(Stream stream, IEnumerable<Resource> resources)
		{
			Export( stream, resources, CultureInfo.InvariantCulture );
		}

		public virtual void Export(Stream stream, IEnumerable<Resource> resources, CultureInfo defaultCulture)
		{
			using( ResXResourceWriter writer = new ResXResourceWriter( new NoCloseStream( stream ) ) )
			{
				foreach( Resource resource in resources )
				{
					string phrase = string.Empty;
					if( resource.Culture == defaultCulture )
					{
						phrase = resource.Phrase;
					}
					else
					{
						Translation translation = resource.FindTranslation( defaultCulture );
						if( translation != null )
						{
							phrase = translation.Phrase;
						}
					}

					ResXDataNode node = new ResXDataNode( resource.Name, phrase );
					node.Comment = resource.Context;
					writer.AddResource( node );
				}
			}
		}

		public virtual string Extension
		{
			get { return ".resx"; }
		}
	}
}